package cc.vv.party.service.impl;

import cc.vv.party.beans.model.VolunteerProjectSignUp
import cc.vv.party.beans.vo.VolunteerProjectSignUpVO
import cc.vv.party.common.base.BaseServiceImpl
import cc.vv.party.common.constants.StatusCode
import cc.vv.party.exception.BizException
import cc.vv.party.mapper.VolunteerProjectMapper
import cc.vv.party.mapper.VolunteerProjectSignUpMapper
import cc.vv.party.param.VolunteerProjectSignUpSaveParam
import cc.vv.party.service.VolunteerProjectSignUpService
import com.baomidou.mybatisplus.mapper.EntityWrapper
import commonx.core.content.transfer
import commonx.core.content.transferEntries
import org.apache.commons.collections.CollectionUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

/**
 * <p>
 * 志愿项目报名信息 服务实现类
 * </p>
 *
 * @author Gyb
 * @since 2018-10-12
 */
@Service
open class VolunteerProjectSignUpServiceImpl : BaseServiceImpl<VolunteerProjectSignUpMapper, VolunteerProjectSignUp>(), VolunteerProjectSignUpService {

    @Autowired
    lateinit var volunteerProjectMapper: VolunteerProjectMapper

    override fun save(param: VolunteerProjectSignUpSaveParam, userId: String): Boolean {

        var volunteerProject = volunteerProjectMapper.selectById(param.volunteerProjectId) ?: throw BizException(StatusCode.MESSAGE_NOT_EXIST.statusCode, "志愿项目信息不存在")

        //判断报名人数是否已经达到项目需求上限
        if((volunteerProject.signupPeople ?: Integer(0)).toInt().plus(1) > volunteerProject.projectQuota!!.toInt()){
            throw BizException(StatusCode.MAXIMUM_NUMBER_OF_APPLICANTS)
        }

        //保存报名信息
        var entity = param.transfer<VolunteerProjectSignUp>()
        entity.createUser = userId
        super.insert(entity)

        //添加项目已报名人数
        volunteerProject.signupPeople = Integer((volunteerProject.signupPeople ?: Integer(0)).toInt().plus(1))

        return volunteerProject.updateById()

    }

    override fun getProSignUpUserList(proId: String): List<VolunteerProjectSignUpVO> {
        var entityList = super.selectList(EntityWrapper<VolunteerProjectSignUp>().where("volunteer_project_id = {0}", proId))
        if(CollectionUtils.isNotEmpty(entityList)){
            return entityList.transferEntries<VolunteerProjectSignUpVO>() as ArrayList
        }
        return emptyList()
    }

}
